package com.dc.web.controller;


import com.dc.constant.MessageConstant;
import com.dc.dao.ShipDao;
import com.dc.dao.ShipRepairDao;
import com.dc.dao.WorkflowShipOldDao;
import com.dc.dao.WorkflowTowShipOilDao;
import com.dc.entity.ShipEntity;
import com.dc.entity.ShipRepairEntity;
import com.dc.entity.WorkflowShipOldEntity;
import com.dc.entity.WorkflowTowShipOilEntity;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.WorkflowListBody;
import com.dc.service.CalibrationService;
import com.dc.service.dto.CalibrationShipOldDto;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;

@Api(tags = "1-单船工序-船体割旧")
@RequestMapping("/api/workflow_ship_old")
@RestController
public class WorkflowShipOldController {

    @Resource
    WorkflowShipOldDao workflowShipOldDao;

    @Resource
    ShipRepairDao shipRepairDao;

    @Resource
    ShipDao shipDao;

    @Resource
    CalibrationService calibrationService;

    @GetMapping("/list")
    public AjaxResult list(WorkflowListBody body) {

        Integer pageNumber = body.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = body.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        Long repairId = body.getRepairId();     // 维修工单id

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(repairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        Page<WorkflowShipOldEntity> resultList = workflowShipOldDao.findByShipRepairEntity(shipRepairEntity, pageRequest);

        CalibrationShipOldDto calibrationShipOldDto = calibrationService.calcShipOld();

        resultList.getContent().forEach(t -> {
            dynamicCalc(t, shipEntity, shipRepairEntity, calibrationShipOldDto);
        });

        return AjaxResult.success(resultList);
    }

    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {

        Optional<WorkflowShipOldEntity> optional = workflowShipOldDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowShipOldEntity shipOilEntity = optional.get();

        ShipRepairEntity shipRepairEntity = shipOilEntity.getShipRepairEntity();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);

        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        CalibrationShipOldDto calibrationShipOldDto = calibrationService.calcShipOld();

        dynamicCalc(shipOilEntity, shipEntity, shipRepairEntity, calibrationShipOldDto);

        return AjaxResult.success(shipOilEntity);
    }


    //
    @PostMapping()
    public AjaxResult add(@RequestHeader HttpHeaders httpHeaders, @RequestBody WorkflowShipOldEntity entity) {

        entity.setId(null);

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        entity.setShipRepairEntity(shipRepairEntity);
        entity.setSubmitTime(new Date());

        WorkflowShipOldEntity save = workflowShipOldDao.save(entity);


        //todo
        CalibrationShipOldDto calibrationShipOldDto = calibrationService.calcShipOld();

        dynamicCalc(save, shipEntity, shipRepairEntity, calibrationShipOldDto);

        return AjaxResult.success(save);
    }

    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody WorkflowShipOldEntity entity) {

        entity.setId(id);

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        entity.setShipRepairEntity(shipRepairEntity);
        entity.setSubmitTime(new Date());

        WorkflowShipOldEntity save = workflowShipOldDao.save(entity);

        CalibrationShipOldDto calibrationShipOldDto = calibrationService.calcShipOld();

        dynamicCalc(save, shipEntity, shipRepairEntity, calibrationShipOldDto);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        workflowShipOldDao.deleteById(id);

        return AjaxResult.success();
    }

    /**
     * 计算动态值
     * @param entity
     * @param shipEntity
     * @param shipRepairEntity
     */

    public static WorkflowShipOldEntity dynamicCalc(WorkflowShipOldEntity entity, ShipEntity shipEntity, ShipRepairEntity shipRepairEntity, CalibrationShipOldDto shipOldDto) {

        //totalLength	切割总长(mm)  	length
        entity.setTotalLength(entity.getLength());

        //gasByUnit		单位耗天然气量标定值
        Double gasByUnit = shipOldDto.getGasByUnit();

        entity.setGasByUnit(gasByUnit);

        //gas		天然气	totalLength * gasByUnit
        try {
            Double gas = entity.getTotalLength() * gasByUnit;
            entity.setGas(gas);
        } catch (Exception e) {
            entity.setGas(0.);
        }

        //o2ByUnit		单位耗氧气量标定值
        Double o2ByUnit = shipOldDto.getO2ByUnit();

        entity.setO2ByUnit(o2ByUnit);

        //o2		氧气量	totalLength * o2ByUnit
        try {
            Double o2 = entity.getTotalLength() * o2ByUnit;
            entity.setO2(o2);
        } catch (Exception e) {
            entity.setO2(0.);
        }

        entity.setShipName(shipEntity.getName());
        entity.setReporter(shipRepairEntity.getUpdater());
        entity.setShipRepairId(shipRepairEntity.getId());
        return entity;
    }

}
